package com.LostAndFound.dao;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.LostAndFound.domain.FoundArticle;
import com.LostAndFound.utils.DataSourceUtils;

public class OrderListForSearchLoserDao {

	// 获取预约领取的记录，且为爱心社发布的（uid=0），寻找失主类型的（whatflag=0），还未失效的（invalidflag=1）
	public int getgetTotalToOrderForEasyUI(String cid) throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql = "select count(*) from article "
				+ " where foundflag = 2 and invalidflag = 1 and whatflag = 0 and uid = 0 ";
		Long total = 0L;
		if(cid.equals("all")) {
			total = (Long) runner.query(sql, new ScalarHandler());
		}else {
			sql = sql + " and cid = ?";
			total = (Long) runner.query(sql, new ScalarHandler(), cid);
		}
		return total.intValue();
	}
	// 此处的预约领取，一定要是管理员所发的寻找失主，也就是要到爱心社领取才行的，a.uid=0
	public List<Map<String, Object>> getOrderListForEasyUI(int startIndex, int pageSize, String cid) throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql = "select a.*,u.*,c.cname from article a,user u,category c "
				+ " where whatflag = 0 and foundflag = 2 and invalidflag = 1 and a.uid = 0 "
				+ " and a.uid = u.uid and a.cid = c.cid ";
		List<Map<String, Object>> mapList = null;
		
		if(cid.equals("all")) {
			sql = sql + " order by a.issuetime desc limit ?,?";
			mapList = runner.query(sql, new MapListHandler(),startIndex,pageSize);
		}else {
			sql = sql + " and a.cid = ? order by a.issuetime desc limit ?,?";
			mapList = runner.query(sql, new MapListHandler(),cid,startIndex,pageSize);
		}
		return mapList;
	}
	//取消认领
	public void handleCancelClaim(String aid) throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql = "update article set foundflag = 1 where aid = ?";
		runner.update(sql, aid);
	}

	public void handleConfirmClaim(FoundArticle foundArticle) throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql = "insert into foundarticle(aid,foundtime,foundinfo) values(?,?,?)";
		Object[] params = {foundArticle.getArticle().getAid(),foundArticle.getFoundTime(),foundArticle.getFoundInfo()};
		runner.update(sql,params);
	}

	public void handleChangeArticleFoundFlag(FoundArticle foundArticle) throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql = "update article set foundflag = 0 where aid = ?";
		runner.update(sql,foundArticle.getArticle().getAid());
	}

}
